<template>
  <!-- 未完成: 点击虚拟背景， input 改为 autocomplete 远程搜索显示 -->

  <div class="search" style="display: none;">
    <p style="color: white;">{{ loading }}</p>
    <p style="color: white;">{{ loaded }}</p>
    <el-row>
      <el-col :span="3" :offset="21">
          <i class="el-icon-circle-close" @click="hiddenSearch" style="border-radius:50%;font-size: 20px;cursor: pointer;background-color: white;"></i>
      </el-col>
    </el-row>
    <el-container id="searchContainer">
      <!-- logo 和 字 -->
      <el-header id="logo">
        <el-row>
          <el-col :span="12" :offset="8">
            <div>
              <i class="iconfont icon-book"></i>
              <span id="font">  Reader site</span>
            </div>
          </el-col>
        </el-row>
      </el-header>
    
      <!--  搜索栏 -->
      <el-footer>
        <el-row>
          <!-- <el-col :span="16" :offset="4"> -->
          <el-col>
            <div>
              <!-- 输入框 -->
              <el-autocomplete
                class = "searchInput"
                v-model="search_input"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入内容"
                @select="handleSelect"
                prefix-icon="el-icon-search"
                :trigger-on-focus="false"
                @keyup.enter.native="handleSearch"
                :select-when-unmatched="false"
                clearable
                :debounce="300"
                value-key="bookName"
                @clear="handleClear"
                ref="autoComplete"
              >
              </el-autocomplete>
              
              <!-- 共 ... 条结果 , 如果为0， 显示没有相关书籍-->
              <!-- 上一页下一页 -->
              <!-- 页数：page -->
              <!-- http://zhuishushenqi.com/search?val=天神殿 &page=2 -->
              <el-scrollbar>
                <div v-show="showResult" class="searchResult" v-infinite-scroll="load" v-cloak>
                  <span>共 {{ totalPages }} 页</span>
                  <span></span>
                  <div v-for="(book, index) in books" :key="index">
                    <book-info :bookInfo="book"></book-info>
                    <el-divider></el-divider>
                  </div>
                  <p v-if="loading">加载中...</p>
                  <p v-if="loaded">没有更多了</p>
                </div>
              </el-scrollbar>
            </div>
          </el-col>
        </el-row>
      </el-footer>
    </el-container>
  </div>
</template>

<script lang="ts">
import { ref,watchEffect, reactive, toRefs, defineComponent, computed } from 'vue'
import { search, getNames } from "@/api/axios/search.ts"
import BookInfo from "@c/ranking/BookInfo.vue"

export default defineComponent({
  name: "search",
  components: {
    BookInfo
  },
  setup() {
    
    // 异步获取的 页数信息
    const totalPages = ref('');
    // 当前页数， 每次初始化为 1
    const pageNum = ref(1);
    // 异步获取的 小说信息
    const books = ref([
      // 信息要与后端同步
      {
        // 书本 id
        id: '',
        // 书名
        name: '',
        // 作者名
        author: '',
        // 大类别
        major: '',
        // 小说简介
        desc: '',
        // 图片链接
        imgUrl: '',
        // 人气
        popularity: '',
        // 读者留存率，信息中已含 %
        keep: ''
      }
    ])
    
    // 显示结果
    const showResult = ref(false)
    
    // 点击 x 按钮，返回界面，隐藏搜索栏，清除之前的内容
    const hiddenSearch = () => {
      // 取消显示
      document.querySelector("div.search").setAttribute('style', 'display: none;')
      // 删除建议
      elAutocomplete.autoComplete.suggestions = []
      // 删除获取的书籍信息
      books.value = []
      // 删除获取的页数
      totalPages.value = ''
      // 是否显示结果变为 false
      showResult.value = false
      // 改变输入值时 显示建议
      elAutocomplete.autoComplete.activated = true
      // 删除搜索栏填的内容
      elAutocomplete.search_input = ''
      // 删除 class, 显示 body 的滚动条
      document.getElementsByTagName("body")[0].classList.remove("body_search_show")
    }
    
    // el-autocomplete 组件相关
    let timeout;
    const elAutocomplete = reactive({
      // 输入
      search_input: '',
      // el-autocomplete 引用
      autoComplete: '',
      // 获取输入建议
      querySearchAsync: (queryString, cb) => {
        clearInterval(timeout);
        timeout = setTimeout(() => {
          getNames(elAutocomplete.search_input).then(res => {
            cb(res.data.names)
          })
        }, 200)
      },
      // 回车后触发
      handleSearch: () => {
        // 初始化 当前页数
        pageNum.value = 1
        // 取消建议显示
        elAutocomplete.autoComplete.activated = false
        // 焦点转为 innerSearch, 解决回车后改变搜索栏内容不显示建议的问题，搜索时需要再次 获取焦点，显示建议
        document.querySelector("div.innerInput>input").focus()
        
        // 显示结果
        search(elAutocomplete.search_input).then(res => {
          books.value = res.data.books
          totalPages.value = res.data.totalPages
          showResult.value = true
        })
      },
      // 文本清除后触发
      handleClear: () => {
        // 初始化 当前页数
        pageNum.value = 1
        // 去掉以前的建议
        elAutocomplete.autoComplete.suggestions = []
        // activated 设为 true, 显示建议， false 时改变输入会不显示
        elAutocomplete.autoComplete.activated = true
      },
      // 选择建议后触发
      handleSelect: (select) => {
        // 初始化 当前页数
        pageNum.value = 1
        search(select.bookName).then(res => {
          books.value = res.data.books
          totalPages.value = res.data.totalPages
          showResult.value = true
        })
      }
    })

    
    // 加载中
    const loading = ref(false)
    // 加载完毕
    const loaded = computed(() => pageNum.value == parseInt(totalPages))
    
    // 正在加载或加载完毕，禁用加载（ load 函数 ）
    const disabled = () => {
      console.log("loading.value==>", loading.value)
      console.log("loaded.value==>", loaded.value)
      console.log("loading.value || loaded.value ==> ", loading.value || loaded.value)
      return loading.value || loaded.value
    }
    
    const load = () => {
      console.log("load()")
      // 正在加载中
      loading.value = true;
      // 当前页数加 1
      pageNum.value += 1
      // 获取新结果
      search(elAutocomplete.search_input, pageNum.value).then(res => {
        // 存在
        if(res.data.books) {
          // 添加到原有 books 里
          for(let i = 0; i < res.data.books.length ; i++) {
            books.value.push(res.data.books[i])
          }
        }
        totalPages.value = res.data.totalPages
        showResult.value = true
      })
      // 加载完毕
      loading.value = false
    }
    
    // 转为 ref 对象，方便使用
    const refComplete = toRefs(elAutocomplete)
    
    return {
      books,
      totalPages,
      hiddenSearch,
      ...refComplete,
      showResult,
      loading,
      loaded,
      load,
      disabled,
    }
    
  }
})
</script>

<style scoped>
/* .searchBody {
  background-color: lightblue !important;
} */
body {
  background-color: #1F2022;
}
.search {
  background-color: #1f2022
}
@keyframes searchAni{
  0% {
    opacity: 0
  }
  50% {
    opacity: 0.5
  }
  100% {
    opacity: 1
  }
}
.search {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: 1px solid saddlebrown;
  z-index: 80;
  background-color: rgba(0,0,0,.8) !important;
  -webkit-backdrop-filter: blur(60px);
  backdrop-filter: blur(60px);
  animation-name: searchAni;
  animation-duration: 0.06s;
}

</style>

<style lang="scss" scoped>

@import "@/static/css/iconfont";

// 引入(版权)字体-方正粗黑宋简体
@font-face {
  font-family: FZCHSJW;
  src: url('@/static/font/FZCHSJW.TTF');
}

// 书本 logo 样式
// $icon_size: 85px;
$icon_size: 33px;
.icon-book {
  font-size: $icon_size;
  color: #2fa0dc;
}
    
// 字体样式
#font {
  font-family: "FZCHSJW";
  // font-size: 65pt;
  font-size: 25pt;
  color: #ccc;
}

$top: 22%;
$l_r: 18%;
#searchContainer {
  // width: 100%;
  // height: 100%;
  top: $top;
  left: $l_r;
  right: $l_r;
  position: absolute;
}

$input_width: 833px;
:deep .el-input__inner {
  // background-color: #7b7b7b ;
  width: $input_width;
  margin-bottom: 20px;
}

.el-scrollbar {
  width: $input_width;
  height: 430px;
}

.searchResult {
  border-radius: 3px;
  width: $input_width;
  padding: 6px;
  background-color: #E6E6E6;
}

.el-divider {
  background-color: #666666;
}
[v-cloak] {
  display: none;
}
</style>
